package com.example.unimpdemo;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.unimpdemo.util.FileUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import io.dcloud.common.DHInterface.ICallBack;
import io.dcloud.feature.sdk.DCUniMPSDK;
import io.dcloud.feature.sdk.Interface.IMenuButtonClickCallBack;
import io.dcloud.feature.sdk.Interface.IOnUniMPEventCallBack;
import io.dcloud.feature.sdk.Interface.IUniMP;
import io.dcloud.feature.sdk.Interface.IUniMPOnCloseCallBack;
import io.dcloud.feature.unimp.DCUniMPJSCallback;

public class MainActivity extends Activity {
    private final String UNI_04E3A11 = "__UNI__04E3A11";
    private final String UNI_B61D13B = "__UNI__B61D13B";
    Context mContext;
    Handler mHandler;
    /**
     * unimp小程序实例缓存
     **/
    HashMap<String, IUniMP> mUniMPCaches = new HashMap<>();
    private DCUniMPSDK dcUniMPSDK;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //灰度模式
        Paint mPaint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        mPaint.setColorFilter(new ColorMatrixColorFilter(cm));
        getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);

        mContext = this;
        mHandler = new Handler();
        setContentView(R.layout.main);
        Button button1 = findViewById(R.id.button1);

        dcUniMPSDK = DCUniMPSDK.getInstance();
        dcUniMPSDK.setUniMPOnCloseCallBack(new IUniMPOnCloseCallBack() {
            @Override
            public void onClose(String appid) {
                Toast.makeText(mContext, appid + "被关闭了", Toast.LENGTH_SHORT).show();
                //小程序被关闭需要对实例缓存删除操作
                if (mUniMPCaches.containsKey(appid)) {
                    mUniMPCaches.remove(appid);
                }
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_04E3A11, MySplashView.class);
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        Button button2 = findViewById(R.id.button2);

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_04E3A11);
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Button button3 = findViewById(R.id.button3);

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    //"pages/tabBar/extUI/extUI" "pages/component/scroll-view/scroll-view"
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_04E3A11, "pages/tabBar/extUI/extUI?aaa=123&bbb=456");
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Button button4 = findViewById(R.id.button4);

        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    final IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_04E3A11, "pages/component/view/view");
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("unimp", "延迟5秒结束 开始关闭当前小程序");
                            uniMP.closeUniMP();
                        }
                    }, 5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Button button5 = findViewById(R.id.button5);

        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JSONObject info = dcUniMPSDK.getAppVersionInfo(UNI_04E3A11);
                if (info != null) {
                    Log.e("unimp", "info===" + info.toString());
                }
            }
        });

        Button button6 = findViewById(R.id.button6);
        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_B61D13B);
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Button button7 = findViewById(R.id.button7);
        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_B61D13B, "pages/sample/send-event");
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Button button8 = findViewById(R.id.button8);
        button8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    IUniMP uniMP = dcUniMPSDK.openUniMP(mContext, UNI_B61D13B, "pages/sample/ext-module");
                    mUniMPCaches.put(uniMP.getAppid(), uniMP);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.button9).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String uniAppId = "__UNI__DBDD32E";
                File file = new File(getCacheDir(), "my_uniapp_cache/" + uniAppId + ".wgt");
                if (!file.exists()) {
                    try {
                        FileUtil.releaseFile(getResources(), R.raw.__uni__dbdd32e, file);
                    } catch (IOException e) {
                        e.printStackTrace();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(v.getContext(), "发生错误:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
                dcUniMPSDK.releaseWgtToRunPathFromePath(uniAppId, file.getAbsolutePath(), new ICallBack() {
                    @Override
                    public Object onCallBack(int code, Object o) {
                        if (code == 1) {//释放wgt完成
                            try {
                                DCUniMPSDK.getInstance().openUniMP(v.getContext(), uniAppId);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {//释放wgt失败
                            Toast.makeText(v.getContext(), "资源释放失败", Toast.LENGTH_SHORT).show();
                        }
                        return null;
                    }
                });
            }
        });


        dcUniMPSDK.setDefMenuButtonClickCallBack(new IMenuButtonClickCallBack() {
            @Override
            public void onClick(String appid, String id) {
                JSONObject appVersionInfo = dcUniMPSDK.getAppVersionInfo(appid);
                Log.i("AppInfo", appVersionInfo.toString());
                switch (id) {
                    case "gy": {
                        Log.e("unimp", "点击了关于" + appid);
                        //宿主主动触发事件
                        JSONObject data = new JSONObject();
                        try {
                            IUniMP uniMP = mUniMPCaches.get(appid);
                            if (uniMP != null) {
                                data.put("sj", "点击了关于");
                                uniMP.sendUniMPEvent("gy", data);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                    case "hqdqym": {
                        IUniMP uniMP = mUniMPCaches.get(appid);
                        if (uniMP != null) {
                            Log.e("unimp", "当前页面url=" + uniMP.getCurrentPageUrl());
                        } else {
                            Log.e("unimp", "未找到相关小程序实例");
                        }
                        break;
                    }
                    case "gotoTestPage":
                        Intent intent = new Intent(mContext, TestPageActivity.class);
                        dcUniMPSDK.startActivityForUniMPTask(appid, intent);
                        break;
                }
            }
        });


        dcUniMPSDK.setOnUniMPEventCallBack(new IOnUniMPEventCallBack() {
            @Override
            public void onUniMPEventReceive(String appid, String event, Object data, DCUniMPJSCallback callback) {
                Log.i("cs", "onUniMPEventReceive    event=" + event);
                //回传数据给小程序
                callback.invoke("收到消息");
            }
        });

        checkPermission();
    }

    /**
     * 检查并申请权限
     */
    public void checkPermission() {
        int targetSdkVersion = 0;
        String[] PermissionString = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        try {
            final PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;//获取应用的Target版本
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //Build.VERSION.SDK_INT是获取当前手机版本 Build.VERSION_CODES.M为6.0系统
            //如果系统>=6.0
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                //第 1 步: 检查是否有相应的权限
                boolean isAllGranted = checkPermissionAllGranted(PermissionString);
                if (isAllGranted) {
                    Log.e("err", "所有权限已经授权！");
                    return;
                }
                // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
                ActivityCompat.requestPermissions(this, PermissionString, 1);
            }
        }
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                //Log.e("err","权限"+permission+"没有授权");
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUniMPCaches.clear();
    }
}